package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author:hx
 * @DateTime:2022/10/4 19:59
 * @Description:
 */
@Configuration //标识为配置类
@EnableWebSecurity //开启注解spring security
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启注解控制权限
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //设置加密方式
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /*//认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .authorities("role.edit");
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //权限访问
        http.authorizeRequests()
                .antMatchers("/static/**","/login").permitAll()
                .anyRequest().authenticated();
        //登录
        http.formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login_process")
                .defaultSuccessUrl("/")
                .failureUrl("/login");
        //注销
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login");
        //csrf禁用
        http.csrf().disable();
        //允许iframe嵌套
        http.headers().frameOptions().disable();
        //处理无权限时访问的页面
        http.exceptionHandling()
                .accessDeniedHandler(new AtguiguAccessDeniedHandler());
    }
}
